iT邦幫忙

2022 iThome 鐵人賽

DAY 8
0
自我挑戰組

30天 Neetcode解題之路系列 第 8

Day 8 - 128. Longest Consecutive Sequence

  • 分享至 

  • xImage
  •  

前言

大家好,我是毛毛。ヾ(´∀ ˋ)ノ
那就開始今天的解題吧~


Question

Given an unsorted array of integers nums, return the length of the longest consecutive elements sequence.

You must write an algorithm that runs in O(n) time.

Example 1:

Input: nums = [100,4,200,1,3,2]
Output: 4
Explanation: The longest consecutive elements sequence is [1, 2, 3, 4]. Therefore its length is 4.

Example 2:

Input: nums = [0,3,7,2,5,8,4,6,0,1]
Output: 9

Constraints:

  • 0 <= nums.length <= 10^5
  • -10^9 <= nums[i] <= 10^9

Think

給一個陣列nums,找出陣列中最長的連續數字序列,並回傳該長度。

首先將陣列排序,方便找出其中的連續數字序列~
每次都會跟下一個數字比較

  • 相減為1
    • 代表為連續的,回傳值(tmp_length)+1
  • 相減為0
    • 代表一樣的,繼續下一個
  • 其他
    • 比較最長的值(longest_length)跟目前暫時存的值(tmp_length)哪個大
  • 最後回傳最長的值

Code

class Solution:
    def longestConsecutive(self, nums: List[int]) -> int:
        # []
        if len(nums) <= 1:
            return len(nums)
        
        # sorted
        nums = sorted(nums)
        #print(nums)
        longest_length = 1
        tmp_length = 1
        
        for index in range(len(nums)-1):
            #print("longest: ", longest_length, "tmp: ", tmp_length)
            if (nums[index+1]-nums[index]) == 1:
                tmp_length += 1
            # the same number should skip!
            elif (nums[index+1]-nums[index]) == 0:
                continue
            else:
                if longest_length <= tmp_length:
                    longest_length = tmp_length
                tmp_length = 1
                
        if longest_length <= tmp_length:
            longest_length = tmp_length
            
        #print("longest_length: ", longest_length)
        return longest_length

Submission


今天就到這邊啦~
大家明天見/images/emoticon/emoticon29.gif


上一篇
Day 7 - 36. Valid Sudoku
下一篇
Day 9 - 125. Valid Palindrome
系列文
30天 Neetcode解題之路30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言